/**
 * Copyright (c) 2008, Keisuke Inoue, Syracuse Unviersity
 * All rights reserved.
 *
 */
package edu.syr.iis.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import edu.syr.iis.web.model.Adjacency;
import edu.syr.iis.web.model.AdjacencyManager;
import edu.syr.iis.web.util.Key;

/**
 * @author kinoue
 *
 */
public class EnterAdjacencyController extends SimpleFormController
{

	private AdjacencyManager adjacencyManager = null;

	/**
	 * Returns a new instance of Adjacency object if "adjacencyId" 
	 * HTTP parameter is specified; other returns instance of object in database 
	 * matching the value of the parameter.
	 * @see Adjacency
	 */

	@Override
	protected Object formBackingObject(HttpServletRequest request)
	{
		System.out.println("Entering EnterAdjacencyController!");

		Adjacency adjacency = null;

		if (request.getParameter(Key.ADJ_ID) != null
				&& request.getParameter(Key.ADJ_ID).trim().length() > 0) 
		{
			int id = Integer.parseInt(request.getParameter(Key.ADJ_ID));
			adjacency = adjacencyManager.getAdjacency(id);
		} 
		else 
		{
			adjacency = new Adjacency();
		}

		System.out.println("Return converlationLabel with ID: " + adjacency.getAdjacencyId());
		return adjacency;
	}   

	@Override
	protected Map referenceData(HttpServletRequest request) throws Exception
	{
		HashMap model = new HashMap();
		model.put(Key.ADJACENCIES, adjacencyManager.getAdjacencies());
		return model;
	}

	@Override
	protected ModelAndView onSubmit(
			HttpServletRequest request,
			HttpServletResponse response,
			Object command,
			BindException errors)
	{
		Adjacency adjacency = (Adjacency) command;

		System.out.println("Entinering onSubmit with ");
		System.out.println(" ID:          " + adjacency.getAdjacencyId());
		System.out.println(" Label:       " + adjacency.getLabel());
		System.out.println(" Description: " + adjacency.getDescription());

		adjacencyManager.saveAdjacency(adjacency);
		return new ModelAndView(getSuccessView());
	}

	public AdjacencyManager getAdjacencyManager()
	{
		return adjacencyManager;
	}

	public void setAdjacencyManager(
			AdjacencyManager adjacencyManager)
	{
		this.adjacencyManager = adjacencyManager;
	}

}
